<template>
  <el-form :model="form" ref="form" :rules="rules" label-width="110px">
    <el-row :gutter="16">
      <el-col :span="12">
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="form.ruleName" placeholder="请输入规则名称" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="预警类型" prop="typeId">
          <classify-select
            ref="classifySelect"
            :selectValue="form.typeId"
            @select="handleClassifySelect"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="预警等级" prop="warningGrade">
          <el-radio-group size="small" v-model="form.warningGrade">
            <el-radio-button :label="1">I级</el-radio-button>
            <el-radio-button :label="2">II级</el-radio-button>
            <el-radio-button :label="3">III级</el-radio-button>
          </el-radio-group>
          <el-tooltip class="item" effect="dark" content="提示文字" placement="top">
            <i class="ml10 el-icon-question fs16"></i>
          </el-tooltip>
        </el-form-item>
      </el-col>
      <!-- <el-col :span="12">
        <el-form-item label="数据级别" prop="dataMode">
          <el-radio-group size="small" v-model="form.dataMode">
            <el-radio-button :label="1">公共级</el-radio-button>
            <el-radio-button :label="2">部门级</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-col>-->
      <el-col :span="12">
        <el-form-item label="运行周期" prop="runCycleType">
          <el-radio-group size="small" v-model="form.runCycleType">
            <el-radio-button :label="1">定时</el-radio-button>
            <el-radio-button :label="2">实时</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col v-show="form.runCycleType === 1">
        <el-form-item>
          <el-row :gutter="10">
            <el-col :span="5">
              <el-select clearable v-model="form.runMonth">
                <el-option v-for="month in 12" :key="month" :value="month" :label="month +'月'" />
              </el-select>
            </el-col>
            <el-col :span="5">
              <el-select clearable v-model="form.runDay">
                <el-option v-for="month in 31" :key="month" :value="month" :label="month + '日'" />
              </el-select>
            </el-col>
            <el-col :span="5">
              <el-select clearable v-model="form.runHour">
                <el-option v-for="month in 24" :key="month" :value="month" :label="month + '时'" />
              </el-select>
            </el-col>
            <el-col :span="5">
              <el-select clearable v-model="form.runMinute">
                <el-option :value="0" :label="0 + '分'" />
                <el-option v-for="month in 59" :key="month" :value="month" :label="month + '分'" />
              </el-select>
            </el-col>
            <el-col :span="4">运行</el-col>
          </el-row>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="开始日期">
          <el-date-picker
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            v-model="form.startDate"
            placeholder="请选择"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="结束日期">
          <el-date-picker
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            v-model="form.endDate"
            placeholder="请选择"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="处置部门">
          <dept-select :style="{width: '230px'}" ref="deptSelect" @select="handleDeptSelect" />
        </el-form-item>
      </el-col>
      <el-col>
        <el-form-item label="数据源" prop="dataSource">
          <el-input type="textarea" :rows="6" placeholder="请输入Sql语句内容" v-model="form.dataSource" />
          <p class="mb0 color-999">变量使用${var + 数字}，数字从1开始，与阀值位置匹配。特殊变量${ruleId}为规则id</p>
        </el-form-item>
      </el-col>
      <el-col>
        <el-form-item label="预警阀值">
          <el-tag
            :key="tag"
            v-for="tag in dynamicTags"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >{{tag}}</el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          ></el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新的阀值</el-button>
        </el-form-item>
      </el-col>
      <el-col>
        <el-form-item>
          <el-button @click="handleEditorBlur" type="primary">解析</el-button>
        </el-form-item>
      </el-col>
      <el-col>
        <el-form-item label="表头定义">
          <el-button
            v-show="repeatData.length > 1 && fieldData.length < repeatData.length"
            class="mb10"
            size="mini"
            type="primary"
            @click="handleAddColumn"
          >新增列</el-button>
          <data-table
            @tableUpdate="handleTableUpdate"
            :repeatData="repeatData"
            :tableData="fieldData"
            ref="dataTable"
          />
        </el-form-item>
      </el-col>
      <el-col>
        <el-form-item label="重复过滤方式">
          <el-select style="width: 100%" @change="handleStyleChange" v-model="form.repeatStyle">
            <el-option :value="0" label="无" />
            <el-option :value="1" label="字段组合" />
            <el-option :value="2" label="SQL匹配" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col v-show="form.repeatStyle === 1">
        <el-form-item
          label="重复过滤字段"
          prop="repeatField"
          :rules=" form.repeatStyle === 1 ? rules.repeatField : []"
        >
          <el-select multiple style="width: 100%" v-model="form.repeatField">
            <el-option v-for="(item,index) in repeatData" :key="index" :value="item" :label="item" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col v-show="form.repeatStyle === 2">
        <el-form-item
          label="重复过滤Sql"
          prop="repeatFilterSql"
          :rules=" form.repeatStyle === 2 ? rules.repeatFilterSql : []"
        >
          <!-- <codemirror
            :style="{height: '500px'}"
            ref="mycode"
            :value="curCode"
            :options="cmOptions"
            class="code"
          ></codemirror>-->
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入Sql语句内容"
            v-model="form.repeatFilterSql"
          />
        </el-form-item>
      </el-col>
      <el-col>
        <el-form-item label="数据时间字段" prop="dataTimeField">
          <el-select clearable style="width: 100%" v-model="form.dataTimeField">
            <el-option v-for="(item,index) in repeatData" :key="index" :value="item" :label="item" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script>
import DataTable from './DataTable'
import ClassifySelect from './ClassifySelect'
import DeptSelect from '@/components/DeptSelect'
// import { codemirror } from 'vue-codemirror'
// import 'codemirror/theme/ambiance.css' // 这里引入的是主题样式，根据设置的theme的主题引入，一定要引入！！
// require('codemirror/mode/javascript/javascript') // 这里引入的模式的js，根据设置的mode引入，一定要引入！！

export default {
  components: {
    DataTable,
    DeptSelect,
    // codemirror,
    ClassifySelect
  },
  computed: {
    getGrade() {
      return this.form.warningGrade
    }
  },
  watch: {
    getGrade: {
      handler(n, o) {
        if (n && n !== o) {
          this.$emit('gradeChange', n)
        }
      },
      deep: true
    }
  },
  data() {
    return {
      form: {},
      rules: {
        ruleName: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
        typeId: [{ required: true, message: '请选择', trigger: 'blur' }],
        warningGrade: [{ required: true, message: '请选择', trigger: 'blur' }],
        runCycleType: [{ required: true, message: '请选择运行周期', trigger: 'blur' }],
        ruleName: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
        dataMode: [{ required: true, message: '请选择数据级别', trigger: 'blur' }],
        dataTimeField: [{ required: true, message: '请选择数据时间字段', trigger: 'blur' }],
        dataSource: [{ required: true, message: '请输入数据源Sql', trigger: 'blur' }],
        repeatFilterSql: [{ required: true, message: '请输入重复过滤Sql', trigger: 'blur' }],
        repeatField: [{ required: true, message: '请输入重复过滤字段', trigger: 'blur' }]
      },
      repeatFilterSql: null,
      loading: false,
      // curCode: '123',
      // cmOptions: {
      //   mode: 'text/javascript',
      //   theme: 'ambiance',
      //   indentUnit: 4, //缩进单位
      //   smartIndent: true, // 自动缩进
      //   tabSize: 4,
      //   styleActiveLine: true,
      //   lineNumbers: true,
      //   line: true,
      //   showCursorWhenSelecting: true,

      //   foldGutter: true,
      //   styleSelectedText: true,
      //   // keyMap: 'sublime',
      //   matchBrackets: true,
      //   extraKeys: { Ctrl: 'autocomplete' },
      //   hintOptions: {
      //     completeSingle: false
      //   }
      // },
      fieldData: [],
      repeatData: [],
      dynamicTags: [],
      inputVisible: false,
      inputValue: null
    }
  },
  methods: {
    handleDeptSelect(value) {
      // console.log('value', value)
      this.$set(this.form, 'chargeDept', value.key)
    },
    handleStyleChange(e) {
      console.log('e', e)
      if (e !== 2) {
        this.$set(this.form, 'repeatFilterSql', null)
      } else if (e !== 1) {
        this.$set(this.form, 'repeatField', null)
      }
    },
    reset() {
      this.form = Object.assign({}, {})
      this.$set(this.form, 'typeId', null)
      this.fieldData = []
      this.repeatData = []
    },
    edit(obj, obj2) {
      console.log('basic', obj, obj2)

      this.form = Object.assign({}, obj)
      const { thresholdValue } = obj2
      if (thresholdValue) {
        // 有值才切割
        this.dynamicTags = thresholdValue.split(',')
      } else {
        this.dynamicTags = []
      }
      // 先调失焦方法
      this.handleEditorBlur()
      this.fieldData = JSON.parse(this.form.tableDefine)
      // 重复过滤方式回显
      if (this.form.repeatFilterField) {
        this.$set(this.form, 'repeatStyle', 1)
        let arr = obj.repeatFilterField.split(',')
        // arr.push(obj.repeatFilterField)
        this.$nextTick(() => {
          this.$set(this.form, 'repeatField', arr)
        })
      } else if (this.form.repeatFilterSql) {
        this.$set(this.form, 'repeatStyle', 2)
      } else {
        this.$set(this.form, 'repeatStyle', 0)
      }
    },
    // 提交时，由这个方法传递数据给父组件
    postData() {
      this.$refs.form.validate(valid => {
        console.log('valid', valid)

        if (valid) {
          // if (this.form.disposalMode === 2) {
          //   // 处置方式为考评时，设置数据
          //   this.$set(this.form, '', this.evalData)
          // }
          let filterField = null
          if (this.form.repeatField) {
            if (this.form.repeatField.length > 1) {
              filterField = this.form.repeatField.join(',')
            } else {
              filterField = this.form.repeatField.join('')
            }
          }
          let arr = []
          if (this.dynamicTags.length > 0) {
            this.dynamicTags.map(v => {
              arr.push(v)
            })
            this.$set(this.form, 'thresholdValue', arr.join(','))
          }

          this.$set(this.form, 'repeatFilterField', filterField) // repeatFilterField1
          this.$set(this.form, 'tableDefine', JSON.stringify(this.fieldData))
          this.$emit('basicData', this.form)
        } else {
          this.$emit('notSubmit', 'basic')
        }
      })
    },
    handleClassifySelect(value) {
      this.$set(this.form, 'typeId', value.id)
    },
    // table 数据更新
    handleTableUpdate(arr) {
      this.fieldData = [...arr]
    },
    handleAddColumn() {
      this.fieldData.push({
        xmId: this.fieldData.length + 1
      })
      console.log('fieldData', this.fieldData)
    },
    handleEditorBlur() {
      if (this.form.dataSource) {
        let field = this.getField(this.form.dataSource, 'select', 'from').trim()
        let arr = []
        // 分割读号，去空格
        // 有as， 获取as到读号，去空格
        // 无as， 取最后一个空格到最后
        let arrFiled = field.split(',')
        // 一直push，中途继续输入，可能导致重复数据
        this.fieldData = []
        this.repeatData = []
        if (arrFiled.length > 0) {
          arrFiled.map((v, index) => {
            v = v.trim()
            if (v.indexOf('as') > 0) {
              v = v.substring(v.lastIndexOf('as') + 2).trim()
            } else if (v.indexOf('.') > 0) {
              v = v.substring(v.lastIndexOf('.') + 1).trim()
            } else if (v.indexOf(' ') > 0) {
              v = v.substring(v.lastIndexOf(' ')).trim()
            }
            this.fieldData.push({
              field: v,
              xmSpecialId: index + 1,
              width: 120
            })
            this.repeatData.push(v)
          })
          this.$emit('repeatData', this.repeatData)
        } else {
          this.$message.error('请输入正确的sql语句')
        }
      }
    },
    // editor 传递出来的html
    handleEditorChange(text) {
      //   const str = html.replace(/<.*?>/gi, '')
      // console.log('str', text)
    },
    getField(str, firstStr, secondStr) {
      if (str == '' || str == null || str == undefined) {
        // "",null,undefined
        return ''
      }
      if (str.indexOf(firstStr) < 0) {
        return ''
      }
      var subFirstStr = str.substring(str.indexOf(firstStr) + firstStr.length, str.length)
      var subSecondStr = subFirstStr.substring(0, subFirstStr.indexOf(secondStr))
      return subSecondStr
    },
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm() {
      let inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
